/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lab3serveurhttp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * @author Mathieu
 */
public class HTTPRequestParser
{
    BufferedReader input;

    public HTTPRequestParser ( InputStream stream )
    {
          input = new BufferedReader(new InputStreamReader(stream));
    }
    
    public HTTPRequestHeader parse ()
    {
        try
        {
            HTTPRequestHeader header = new HTTPRequestHeader ( );
            StringBuilder contentBuilder = new StringBuilder ( );
            String content;
            String str;
            while ( ! (str=input.readLine()).equals("") )
            {
                contentBuilder.append(str);
                contentBuilder.append ( "\r\n" );
            }
            
            content = contentBuilder.toString ( ); 
            
            header.Get = getValue ( content, "GET (.*) HTTP/[0-9].[0-9]" );
            header.Host = getValue ( content, "HOST: (.*)" );
            header.Connection = getValue ( content, "Connection: (.*)" );
            header.UserAgent = getValue ( content, "User-agent: (.*)" );            
            header.AcceptLangage = getValue ( content, "Accept-language: (.*)" );
            
            return header;
        }
        catch(Exception elephant)
        {
            return null;
        }
    }
    
    private String getValue ( String line, String regex )
    {
        try
        {
            Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
            String str = line;
            Matcher m = p.matcher(str);
            m.find();

            return m.group ( 1 );
        }
        catch ( Exception e )
        {
            return "";
        }
    }
}
